package util

import (
	"encoding/json"
	"fmt"
	"net/http"
	"sync"

	"github.com/gorilla/websocket"
	"openzbox.com/frame/echo"
	models "openzbox.com/frame/echo/models/sl_gw01"
)

type wsData struct {
	Name string
	Data string
	Type string
}

var wsDatas = wsData{}
var (
	upgrader = websocket.Upgrader{
		//ReadBufferSize:   1024,
		//WriteBufferSize:  1024,
		CheckOrigin: checkOrigin,
		//HandshakeTimeout: 5 * time.Second,
	}
	upgrader2 = websocket.Upgrader{
		CheckOrigin: checkOrigin,
	}
	ClientWS  *websocket.Conn
	ClientWS2 *websocket.Conn
	portname  string
)

// 允许websocket跨域
func checkOrigin(r *http.Request) bool {
	return true
}
func HandleWebSocket(c echo.Context) error {
	//fmt.Println("open WebSocketService", c.QueryParam("id"))
	portname = c.QueryParam("id")
	ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
	if err != nil {
		fmt.Println("升级为WebSocket连接失败：", err)
		return err
	}
	//创建的连接放入map
	ClientWS = ws
	// 在这里处理WebSocket消息
	// for {
	// 	//	messageType, message, err := ws.ReadMessage()
	// 	err = ws.ReadJSON(&wsDatas) //ws.ReadMessage()
	// 	if err != nil {
	// 		fmt.Println("读取消息失败：", err)
	// 		break
	// 	}
	// 	//fmt.Println("收到消息", wsDatas)
	// 	//fmt.Println("收到消息2", messageType)

	// 	// 在这里处理收到的消息，并可以通过conn.WriteMessage()发送消息给客户端
	// }
	return nil
}
func HandleWebSocket2(c echo.Context) error {
	ws, err := upgrader2.Upgrade(c.Response(), c.Request(), nil)
	if err != nil {
		fmt.Println("升级为WebSocket连接失败：", err)
		return err
	}
	//创建的连接放入map
	ClientWS2 = ws
	return nil
}

var mu sync.Mutex

func WriteMessage(data interface{}, types string) {
	mu.Lock()
	ws := ClientWS
	if ws != nil {
		//err := ws.WriteMessage(websocket.TextMessage, bytes.Trim(dat, "\x00"))
		datas := models.WebsocketData{
			Data: data,
			Type: types,
		}
		// 将Data对象序列化为JSON格式的字节切片
		jsonData, err := json.Marshal(datas)
		if err != nil {
			fmt.Println("序列化JSON2时发生错误:", err)
		} else {
			err := ws.WriteMessage(websocket.TextMessage, jsonData)
			if err != nil {
				//fmt.Println("WsWriteMessage错误", err)
			}
		}

	}
	mu.Unlock() //解锁

}
func WriteMessage2(data interface{}, types string) {
	mu.Lock()
	ws := ClientWS2
	if ws != nil {
		//err := ws.WriteMessage(websocket.TextMessage, bytes.Trim(dat, "\x00"))
		datas := models.WebsocketData{
			Data: data,
			Type: types,
		}
		// 将Data对象序列化为JSON格式的字节切片
		jsonData, err := json.Marshal(datas)
		if err != nil {
			fmt.Println("序列化JSON2时发生错误:", err)
		} else {
			err := ws.WriteMessage(websocket.TextMessage, jsonData)
			if err != nil {
				//fmt.Println("WsWriteMessage错误", err)
			}
		}

	}
	mu.Unlock() //解锁

}
